package phoenit;



import org.junit.Before;
import org.junit.Test;

import java.sql.*;

public class Phoenit {
    Connection connection = null;
    String sql = "";
    ResultSet rs = null;
    PreparedStatement ps = null;
    @Before
    public void getConnection(){
        try {
            Class.forName("org.apache.phoenix.jdbc.PhoenixDriver");
            connection = DriverManager.getConnection("jdbc:phoenix:master:2181");
        }catch (Exception e){
            e.fillInStackTrace();
        }
    }
    @Test
    public void createTable() throws SQLException {
        sql = "create table haha(id integer primary key,name varchar(20),age integer)";
        ps = connection.prepareStatement(sql);
        ps.execute();
        ps.close();
        connection.close();
        System.out.println("running" + sql);
    }
    @Test
    public void select() throws SQLException {
        sql = "select * from user";
        ps = connection.prepareStatement(sql);
        rs = ps.executeQuery();
        while (rs.next()) {
            System.out.println(rs.getString("NAME"));
        }
        ps.close();
        connection.close();
    }
    @Test
    public void insert() throws SQLException {
        sql = "upsert into user (id,name,sex)values(1,'wangwu','nan')";
        ps = connection.prepareStatement(sql);
        int i = ps.executeUpdate();
        connection.commit();
        ps.close();
        connection.close();
        if(i == 1){
            System.out.println("添加成功");
        }else{
            System.out.println("添加失败");
        }
    }
    @Test
    public void delete() throws SQLException {
        sql = "delete from user where id=1";
        ps = connection.prepareStatement(sql);
        int i = ps.executeUpdate();
        connection.commit();
        ps.close();
        connection.close();
        if(i == 1){
            System.out.println("删除成功");
        }else{
            System.out.println("删除失败");
        }
    }
    @Test
    public void update() throws SQLException {
        sql = "upsert into user (id,name,sex)values(2,'zhaoliu','nan')";
        ps = connection.prepareStatement(sql);
        int i = ps.executeUpdate();
        connection.commit();
        ps.close();
        connection.close();
        if(i == 1){
            System.out.println("更新成功");
        }else{
            System.out.println("更新失败");
        }
    }
}
